package com.zhanggm.springcloud.jpa.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zhanggm.springcloud.jpa.dao.StudentDao;
import com.zhanggm.springcloud.jpa.entity.Student;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author Zgm
 * @version 1.0
 * @date 2020/6/27 0027 8:44
 */
@Service
public class StudentService {

    @Autowired
    private StudentDao studentDao;

    /**
     * 分页查询
     * @param student
     * @param page
     * @param size
     * @return
     */
    public Page<Student> getPageInfo(Student student,Integer page,Integer size){
        Specification<Student> specification = new Specification<Student>() {
            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(student.getName()!=null){
                    criteriaBuilder.like(root.get("name"),"%".concat(student.getName()).concat("%"));
                }
                if(student.getClassesName()!=null){
                    Predicate like = criteriaBuilder.like(root.get("classes").get("name"), "%".concat(student.getClassesName()).concat("%"));
                    predicates.add(like);
                }

                if(student.getHobbyName()!=null){
                    Predicate like = criteriaBuilder.like(root.join("hobbies").get("name"), "%".concat(student.getHobbyName()).concat("%"));
                    predicates.add(like);
                }

                if(student.getHobbyId()!= null){
                    Predicate equal = criteriaBuilder.equal(root.join("hobbies").get("id"), student.getHobbyId());
                    predicates.add(equal);
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Pageable pageable = PageRequest.of(page-1,size, Sort.Direction.DESC,"name");
        return studentDao.findAll(specification,pageable);
    }
}
